import { useHttpRequest } from '@/api/chunfeng/apiRequest'
import { UnwrapNestedRefs } from '@vue/reactivity'

import { reactive, ref, watch } from 'vue'

import { ExpenseData, QueryExpenseParam } from '@/api/chunfeng/finance/expense/interfaces'
import moment from 'moment'
import { useExpenseApi } from '@/api/chunfeng/finance/expense'

export const useExpenseListFunctions = () => {
  // name: 'ReceiptList',
  const { executeQueryRequest } = useHttpRequest()
  const { queryExpense } = useExpenseApi()

  const resultDataSet = ref(Array<ExpenseData>())

  const paginationConfig = reactive({
    showSizeChanger: true,
  })

  const dateRangeRef = ref<moment.Moment[]>([])

  const queryParams: UnwrapNestedRefs<QueryExpenseParam> = reactive({
    name: undefined,
    expenseTypeId: undefined,
    occurredStart: undefined,
    occurredEnd: undefined,
  })

  watch(
    () => dateRangeRef,
    (newVal) => {
      if (newVal.value && newVal.value.length > 1) {
        queryParams.occurredStart = newVal.value[0]
        queryParams.occurredEnd = newVal.value[1]
      }
    },
    { deep: true },
  )

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型名称',
      dataIndex: 'expenseTypeName',
      key: 'expenseTypeName',
    },
    {
      title: '发生日期',
      dataIndex: 'occurredAt',
      key: 'occurredAt',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '创建日期',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },

    {
      title: '操作',
      key: 'action',
      slots: { customRender: 'action' },
    },
  ]

  function reset() {
    queryParams.name = undefined
    queryParams.expenseTypeId = undefined
    queryParams.occurredStart = undefined
    queryParams.occurredEnd = undefined
  }

  function query() {
    resultDataSet.value.length = 0
    executeQueryRequest(queryExpense(queryParams), (results: ExpenseData[]) => {
      resultDataSet.value.push(...results)
    })
  }

  function expenseTypeSelected(expenseTypeId: string) {
    queryParams.expenseTypeId = expenseTypeId
  }

  return {
    paginationConfig,
    queryParams,
    columns,
    reset,
    query,
    resultDataSet,
    expenseTypeSelected,
    dateRangeRef,
  }
}
